package pre.lxm.demo.chart;


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import pre.lxm.demo.chart.bean.RecordBean;

public class HorizontalChartView extends View {
    private static final String TAG = "ChartView";


    private Paint mPaint;
    private TextPaint mTextPaint;
    private Context mContext;

    private int fixNumber = 12;

    private int mWidth, mHeight;
    private int itemHeight, itemWidth;
    private int leftPadding = 20, rightPadding = 20;
    private int lineHeight = 4;

    private String[] resultStr = new String[]{"胜", "平", "负"};


    private List<RecordBean> mRecordList;

    public HorizontalChartView(Context context) {
        this(context, null);
    }

    public HorizontalChartView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public HorizontalChartView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        init();
    }

    private void init() {
        initPaint();
        initTextPaint();
        mRecordList = new ArrayList<>();
        initData();
        mWidth = getScreenWidth(mContext);
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setColor(Color.parseColor("#E1E1E1"));
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setStrokeWidth(lineHeight);
    }

    private void initTextPaint() {
        mTextPaint = new TextPaint();
        mTextPaint.setTextSize(40);
        mTextPaint.setStrokeWidth(6);
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setStyle(Paint.Style.FILL);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
//        if (widthMode == MeasureSpec.EXACTLY) {
//            mWidth = MeasureSpec.getSize(widthMeasureSpec);
//        } else {
//            mWidth = getScreenWidth(mContext);
//            itemWidth = (getScreenWidth(mContext) - leftPadding - rightPadding) / (fixNumber + 2);
//        }

        itemWidth = (mWidth - leftPadding - rightPadding) / (fixNumber + 2);
        mHeight = MeasureSpec.getSize(heightMeasureSpec);
        itemHeight = (mHeight - lineHeight * 2) / 4;
        setMeasuredDimension(mWidth, mHeight);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawCore(canvas);
        drawRecord(canvas);
    }


    private void drawCore(Canvas canvas) {

        //绘制横线
        mPaint.setStrokeWidth(lineHeight);
        mPaint.setColor(Color.parseColor("#E1E1E1"));
        canvas.drawLine(0, lineHeight, mWidth, lineHeight, mPaint);
        canvas.drawLine(0, lineHeight + itemHeight, mWidth, lineHeight + itemHeight, mPaint);


        //轮次
        canvas.save();
        canvas.translate(leftPadding, 0);
        Rect rect = drawText(canvas, mTextPaint, "轮次", itemWidth, itemHeight);

        //胜平负
        mTextPaint.setColor(Color.BLACK);
        for (int i = 0; i < resultStr.length; i++) {
            canvas.translate(0, itemHeight + lineHeight * 2);
            drawText(canvas, mTextPaint, resultStr[i], itemWidth, itemHeight);
        }
        canvas.restore();


        //虚线
        canvas.save();
        mPaint.setStrokeWidth(lineHeight);
        canvas.translate(leftPadding + itemWidth, itemHeight + lineHeight * 2);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.parseColor("#CECECE"));
        mPaint.setAntiAlias(true);
        PathEffect pathEffect = new DashPathEffect(new float[]{10, 10, 10, 10}, 1);
        for (int i = 0; i < 3; i++) {
            mPaint.setPathEffect(pathEffect);
            Path path = new Path();
            path.moveTo(0, itemHeight / 2);
            path.lineTo(mWidth - rightPadding, itemHeight / 2);
            canvas.drawPath(path, mPaint);
            canvas.translate(0, itemHeight);
        }
        canvas.restore();

    }

    private void initData() {
        mRecordList = new ArrayList<>();
        String[] results = new String[]{"3", "1", "0"};
        String[] hosts = new String[]{"h", "g"};

        for (int i = 1; i <= 16; i++) {
            RecordBean recordBean = new RecordBean();
            recordBean.setTurn(i + "");
            recordBean.setResult(results[new Random().nextInt(3)]);
            recordBean.setIsHost(hosts[new Random().nextInt(2)]);
            mRecordList.add(recordBean);
        }
    }

    private void drawRecord(Canvas canvas) {
        canvas.save();
        canvas.translate(itemWidth + leftPadding, 0);
        for (int i = 0; i < mRecordList.size(); i++) {
            drawText(canvas, mTextPaint, mRecordList.get(i).getTurn(), itemWidth, itemHeight);
            canvas.translate(itemWidth, 0);
        }
        canvas.restore();

    }

//    public void refreshData(List<RecordBean> recordList) {
//        mRecordList.clear();
//        mRecordList.addAll(recordList);
//        invalidate();
//    }

    private Rect drawText(Canvas canvas, TextPaint textPaint, String txtString, int txtMeasureWidth, int txtMeasureHeight) {
        Rect mRect = new Rect();
        mTextPaint.getTextBounds(txtString, 0, txtString.length(), mRect);
        Paint.FontMetricsInt fontMetrics = mTextPaint.getFontMetricsInt();
//        float baseline = txtMeasureHeight / 2 + textPaint.getTextSize() / 2 - textPaint.getFontMetrics().descent;
        float baseline = txtMeasureHeight / 2 + (fontMetrics.descent - fontMetrics.ascent) / 2 - fontMetrics.descent;
        canvas.drawText(txtString, (mRect.width()) / 2, baseline, mTextPaint);
        return mRect;
    }


    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }
}
